package com.Q.podcastq;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.Q.items.ItemListBaseAdapter;
import com.Q.items.item;
import com.Q.podcastq.BD.BD;

public class ListActivity extends Activity {
	private ListView lv;
	BD basededatoshelper;
	private TextView titulo;
	static String nombrelista;
	ArrayList<item> items = com.Q.podcastq.MainActivity.items;
	private boolean descargado = com.Q.podcastq.MainActivity.descargado;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		basededatoshelper = new BD(this,"QCU", null, 20);

		Bundle extras = getIntent().getExtras();
		if(extras.getBoolean("DESCARGADOS")){
			new AsyncTaskfotos().execute("1");

			nombrelista = "Podcasts descargados";
		}
		else{
			new AsyncTaskfotos().execute("0");

			nombrelista = "Podcasts disponibles";
		}


	}
	private class AsyncTaskfotos extends AsyncTask<String, String, String> {

		ProgressDialog dialog;
		@Override
		protected void onPreExecute() {
			try {
				dialog = new ProgressDialog(ListActivity.this);
				dialog.setTitle(ListActivity.this.getString(R.string.cargando));
				dialog.setMessage(ListActivity.this.getString(R.string.obtInfoServer));
				dialog.setCancelable(true);
				dialog.show();
			} catch (final Exception e) {
				Log.e("Error", e.getMessage());
			}
		}
		@Override
		protected void onPostExecute(final String result) {


			setContentView(R.layout.list_activity);
			lv = (ListView) findViewById(R.id.listView1);

			titulo = (TextView) findViewById(R.id.ListaNombre);
			titulo.setText(nombrelista);

			lv.setAdapter(new ItemListBaseAdapter(ListActivity.this, items));

			lv.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
					Intent returnIntent = getIntent();
					setResult(RESULT_OK,returnIntent);
					item itemito = (item)lv.getItemAtPosition(position);
					returnIntent.putExtra("pos", itemito.getId());
					finish();
				}
			}); 

			dialog.dismiss();

		}
		@Override
		protected String doInBackground(String... params) {
			item aux;

			items.clear();
			SQLiteDatabase db;
			String idmax="0";
			db = basededatoshelper.getReadableDatabase();
			String[] col = {"id","titulo","author","duracion","fecha","foto","fotodescargada", "url", "descargado"};	
			Cursor cursor;
			String[] arg = {"1"};
			if("1".equalsIgnoreCase(params[0])){
				cursor = db.query("PODCAST",col , "descargado=?" , arg , null, null , "id DESC" , null);
			}
			else {
				cursor = db.query("PODCAST",col , null , null , null, null , "id DESC" , "30");
			}
			cursor.moveToFirst();
			while(!cursor.isAfterLast()){
				aux = new item();
				aux.setImageNumber(getBitmapFromURL(cursor.getString(5),cursor.getInt(6),cursor.getString(0) ));
				aux.setId(cursor.getString(0));
				aux.setName(cursor.getString(1));
				aux.setItemDescription(cursor.getString(3));
				String[] parsead = cursor.getString(4).split(",")[1].split(" ");
				aux.setPrice(parsead[1]+" "+parsead[2]+" "+parsead[3]);
				aux.setContexto(ListActivity.this);
				aux.setUrl(cursor.getString(7));
				aux.setDescargado(cursor.getString(8));
				items.add(aux); 
				cursor.moveToNext();
			}
			cursor.close();
			db.close();


			return null;
		}

		public Bitmap getBitmapFromURL(String src, Integer descargada, String id) {
			try{
				Bitmap myBitmap = null;
				if(descargada==0){
					URL url = new URL(src);
					InputStream input = url.openStream();
					myBitmap = BitmapFactory.decodeStream(input);
					Log.e("Bitmap","returned");
					String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
					OutputStream outStream = null;
					File wallpaperDirectory = new File(extStorageDirectory+"/Qpodcast/");
					// have the object build the directory structure, if needed.
					wallpaperDirectory.mkdirs();
					extStorageDirectory += "/Qpodcast";
					File file = new File(extStorageDirectory, id+".QPJPEG");
					outStream = new FileOutputStream(file);
					myBitmap.compress(Bitmap.CompressFormat.JPEG, 80, outStream);
					outStream.flush();
					outStream.close();
					SQLiteDatabase db;
					String idmax="0";
					db = basededatoshelper.getWritableDatabase();
					db.execSQL("UPDATE PODCAST SET fotodescargada='1', foto='"+extStorageDirectory+"/"+id+".QPJPEG' WHERE id ='"+id+"'" );


				}else{
					myBitmap = BitmapFactory.decodeFile(src);
				}
				return myBitmap;

			} catch (Exception e) {
				e.printStackTrace();
				Log.e("Exception",e.getMessage());
				return null;
			}
		}

	}
}